﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace PatsTracks
{
    public partial class Form1 : Form
    {
        PatsTracksMain mainDB;
        SortedDictionary<string, int> reportDict = new SortedDictionary<string, int>();
        public Form1()
        {
            InitializeComponent();
            mainDB = new PatsTracksMain();
            mainDB.Load();
            try
            {
                reportDict = getreports();
            }catch {};
            populateLists();
        }
        public void populateLists()
        {
            CustList.Items.Clear();
            BuyCust.Items.Clear();
            SellCust.Items.Clear();
            MedList.Items.Clear();
            SellMedia.Items.Clear();
            RewardCustList.Items.Clear();
            RewardProgramList.Items.Clear();
            //take care of the customer lists
            foreach (PatsCustomer c in mainDB.getAllCustomers())
            {
                CustList.Items.Add(c);
                BuyCust.Items.Add(c);
                SellCust.Items.Add(c);
                RewardCustList.Items.Add(c);
            }
            //then the media lists
            foreach (Media m in mainDB.getAllMedia())
            {
                MedList.Items.Add(m);
                if (!m.sold)
                    SellMedia.Items.Add(m);
            }
            foreach (var s in mainDB.rewardPrograms)
            {
                RewardProgramList.Items.Add(s.Key);
            }
            chart1.Series["Media"].Points.Clear();
            foreach (KeyValuePair<string, int> k in reportDict)
            {
                chart1.Series["Media"].Points.AddXY(k.Key, k.Value);
            }
        }
        public void savereports(SortedDictionary<string, int> dictionary)
        {
            FileStream fs = new FileStream("reports.dat", FileMode.OpenOrCreate, FileAccess.Write);
            BinaryWriter writer = new BinaryWriter(fs);
            writer.Write(dictionary.Count);
            foreach (var kvp in dictionary)
            {
                writer.Write(kvp.Key);
                writer.Write(kvp.Value);
            }
            writer.Flush();
            fs.Close();
        }
        public SortedDictionary<string, int> getreports()
        {
            FileStream fs = new FileStream("reports.dat", FileMode.OpenOrCreate, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            int count = reader.ReadInt32();
            var dictionary = new SortedDictionary<string, int>();
            for (int n = 0; n < count; n++)
            {
                var key = reader.ReadString();
                var value = reader.ReadInt32();
                dictionary.Add(key, value);
            }
            fs.Close();
            return dictionary;
        }
        private void button2_Click(object sender, EventArgs e)
        { // I forgot to change the name of this button, chaning it now just causes problems.
          // This is the Clear Data button on the View/Manage Media page
            MedTitle.Clear();
            MedArtist.Clear();
            MedGenre.Clear();
            MedDecade.Clear();
            MedSalePrice.Value = 0.0M;
            MedPurchasePrice.Value = 0.0M;
            MedSerial.Clear();
            MedList.ClearSelected();
        }

        private void CustClear_Click(object sender, EventArgs e)
        {
            CustName.Clear();
            CustAddress.Clear();
            CustPhone.Clear();
            CustPurchHist.Clear();
            CustSaleHist.Clear();
            CustList.ClearSelected();
            CustID.Clear();
        }

        private void BuySellClear_Click(object sender, EventArgs e)
        {
            BuyTitle.Clear();
            BuyArtist.Clear();
            BuyGenre.Clear();
            BuyDecade.Clear();
            BuySellPrice.Value = (Decimal)0.0;
            BuyCust.ClearSelected();
        }

        private void MedUpdateAdd_Click(object sender, EventArgs e)
        {
            try
            {
                int x = Int32.Parse(MedSerial.Text);
                mainDB.buyOrUpdateMedia(MedTitle.Text, MedArtist.Text, MedGenre.Text, MedDecade.Text, (Double)MedPurchasePrice.Value, (Double)MedSalePrice.Value, x);
                populateLists();
                mainDB.Save();
            }
            catch
            {
                MessageBox.Show("Media Item not selected!");
                //mainDB.buyOrUpdateMedia(MedTitle.Text, MedArtist.Text, MedGenre.Text, MedDecade.Text, (Double)MedPurchasePrice.Value, (Double)MedSalePrice.Value);
            }
        }

        private void MedList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MedList.SelectedItem == null) return;
            string s = MedList.SelectedItem.ToString();
            s = s.Substring(s.LastIndexOf(":") + 2);
            int x = Int32.Parse(s);
            Media media = mainDB.findMedia(x);

            MedTitle.Text = media.Title;
            MedArtist.Text = media.Artist;
            MedGenre.Text = media.Genre;
            MedDecade.Text = media.Decade;
            MedSalePrice.Value = (Decimal)media.SalePrice;
            MedPurchasePrice.Value = (Decimal)media.PurchasePrice;
            MedSerial.Text = media.getSerialNumber.ToString();
        }

        private void CustUpdateAdd_Click(object sender, EventArgs e)
        {
            try
            {
                int x = Int32.Parse(CustID.Text);
                mainDB.addOrUpdateCustomer(CustName.Text, CustPhone.Text, CustAddress.Text, x);
            }
            catch
            {

                mainDB.addOrUpdateCustomer(CustName.Text, CustPhone.Text, CustAddress.Text);
            }
            populateLists();
            mainDB.Save();
        }

        private void CustList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CustList.SelectedItem == null) return;
            string s = CustList.SelectedItem.ToString();
            s = s.Substring(s.LastIndexOf(":") + 2);
            int x = Int32.Parse(s);
            PatsCustomer cust = mainDB.findCustomer(x);

            CustName.Text = cust.Name;
            CustAddress.Text = cust.Address;
            CustID.Text = cust.CustomerKey.ToString();
            CustPhone.Text = cust.Phone;
            CustPurchHist.Clear();
            CustSaleHist.Clear();
            foreach (Media m in cust.getAllPurchases(mainDB.allMedia))
            {
                CustPurchHist.AppendText(m.ToString() + "\n");
            }
            foreach (Media m in cust.getAllSales(mainDB.allMedia))
            {
                CustSaleHist.AppendText(m.ToString() + "\n");
            }
        }
        private void BuyMediaButton_Click(object sender, EventArgs e)
        {
            if (BuyCust.SelectedItem == null)
            {
                MessageBox.Show("No customer selected!");
                return;
            }
            MessageBox.Show(mainDB.buyOrUpdateMedia(BuyTitle.Text, BuyArtist.Text, BuyGenre.Text, BuyDecade.Text, (double)BuySellPrice.Value));
   
            string sellerString = BuyCust.SelectedItem.ToString();
            sellerString = sellerString.Substring(sellerString.LastIndexOf(":") + 2);
            int sellerID = Int32.Parse(sellerString);
            PatsCustomer Seller = mainDB.findCustomer(sellerID);

            mainDB.buyMedia(mainDB.lastMediaSN, (Double)BuySellPrice.Value, sellerID);
            populateLists();
            mainDB.Save();
        }

        private void SellMediaButton_Click(object sender, EventArgs e)
        {
            if (BuyCust.SelectedItem == null) return;

            string buyerString = BuyCust.SelectedItem.ToString();
            buyerString = buyerString.Substring(buyerString.LastIndexOf(":") + 2);
            int buyerID = Int32.Parse(buyerString);
            PatsCustomer buyer = mainDB.findCustomer(buyerID);
            mainDB.Save();
        }

        private void BuyAddClear_Click(object sender, EventArgs e)
        {
            BuyAddCustName.Clear();
            BuyAddCustAddress.Clear();
            BuyAddCustPhone.Clear();
        }

        private void BuyAddCust_Click(object sender, EventArgs e)
        {
            MessageBox.Show(mainDB.addOrUpdateCustomer(BuyAddCustName.Text, BuyAddCustPhone.Text, BuyAddCustAddress.Text));
            populateLists();
            mainDB.Save();
        }

        private void SellClearCust_Click(object sender, EventArgs e)
        {
            SellAddCustName.Clear();
            SellAddCustAddress.Clear();
            SellAddCustPhone.Clear();
        }
        private void SellAddCust_Click(object sender, EventArgs e)
        {
            MessageBox.Show(mainDB.addOrUpdateCustomer(SellAddCustName.Text, SellAddCustPhone.Text, SellAddCustAddress.Text));
            populateLists();
            mainDB.Save();
        }

        private void SellToCust_Click(object sender, EventArgs e)
        {
            if ((SellMedia.SelectedItem == null) || (SellCust.SelectedItem == null))
            {
                MessageBox.Show("Please select a customer and a media item");
                return;
            }

            string purchaserString = SellCust.SelectedItem.ToString();
            purchaserString = purchaserString.Substring(purchaserString.LastIndexOf(":") + 2);
            int purchaserID = Int32.Parse(purchaserString);
            PatsCustomer purchaser = mainDB.findCustomer(purchaserID);

            string toSellString = SellMedia.SelectedItem.ToString();
            toSellString = toSellString.Substring(toSellString.LastIndexOf(":") + 2);
            int toSellSN = Int32.Parse(toSellString);
            Media toSell = mainDB.findMedia(toSellSN);

            double soldPrice = (Double)SellPrice.Value;
            RewardProgram cReward = purchaser.rewardProgram;
            if (cReward.isPercent() && cReward.PercentOff() > 0)
            {
                MessageBox.Show("You saved " + (soldPrice * .01 * cReward.PercentOff()).ToString("F2") + " dollars!");
                soldPrice = soldPrice - soldPrice * .01 * cReward.PercentOff();
            }
            else if (purchaser.rewardProgram.GetFree() > 0)
            {
                if (purchaser.getNumBoughtItems() % (cReward.ToBuy() + cReward.GetFree()) >= cReward.ToBuy())
                {
                    soldPrice = 0;
                    MessageBox.Show("Customer gets this one on us!");
                }
                else MessageBox.Show("Media successfully sold to customer!");
            }else MessageBox.Show("Media successfully sold to customer!");

            mainDB.sellMedia(toSellSN, soldPrice, purchaserID);
            string mykey = ((int)soldPrice).ToString();
            if(reportDict.ContainsKey(mykey))
            {
                reportDict[mykey] = reportDict[mykey] +1;
            }
            else
                reportDict.Add(mykey,1);
            populateLists();
            mainDB.Save();
            savereports(reportDict);
        }

        private void MedShowAll_Click(object sender, EventArgs e)
        {
            populateLists();
        }

        private void MedShowInStock_Click(object sender, EventArgs e)
        {
            MedList.Items.Clear();
            foreach (Media m in mainDB.getAllMedia())
            {
                if (!m.sold)
                    MedList.Items.Add(m);
            }
        }

        private void MedShowSold_Click(object sender, EventArgs e)
        {
            MedList.Items.Clear();
            foreach (Media m in mainDB.getAllMedia())
            {
                if (m.sold)
                    MedList.Items.Add(m);
            }
        }

        private void MedClearSearch_Click(object sender, EventArgs e)
        {
            MedSearch.Clear();
        }

        private void MedDisplaySearch_Click(object sender, EventArgs e)
        {
            string toSearch = MedSearch.Text;
            if (MedSearchAlbumRadio.Checked)
                searchMedia(toSearch, "ALBUM", MedList);
            else if (MedSearchArtistRadio.Checked)
                searchMedia(toSearch, "ALBUM", MedList);
            else if (MedSearchGenreRadio.Checked)
                searchMedia(toSearch, "ALBUM", MedList);
            else
                MessageBox.Show("What do you want me to search by?");
        }

        private void CustClearSearch_Click(object sender, EventArgs e)
        {
            CustSearch.Clear();
        }

        private void CustDisplaySearch_Click(object sender, EventArgs e)
        {
            string toSearch = CustSearch.Text;
            if (CustSearchNameRadio.Checked)
                searchCustomers(toSearch, "NAME", CustList);
            else if (CustSearchAddressRadio.Checked)
                searchCustomers(toSearch, "ADDRESS", CustList);
            else if (CustSearchPhoneRadio.Checked)
                searchCustomers(toSearch, "PHONE", CustList);
            else MessageBox.Show("What do you want me to search by?");
        }
        private void CustDisplayAll_Click(object sender, EventArgs e)
        {
            populateLists();
        }

        private void BuyCustSearchClear_Click(object sender, EventArgs e)
        {
            BuyCustSearch.Clear();
        }
        private void BuyCustSearchDislplay_Click(object sender, EventArgs e)
        {
            string toSearch = BuyCustSearch.Text;
            if (BuyCustSearchNameRadio.Checked)
                searchCustomers(toSearch, "NAME", BuyCust);
            else if (BuyCustSearchAddressRadio.Checked)
                searchCustomers(toSearch, "ADDRESS", BuyCust);
            else if (BuyCustSearchPhoneRadio.Checked)
                searchCustomers(toSearch, "PHONE", BuyCust);
            else MessageBox.Show("What do you want me to search by?");
        }

        private void SellMediaSearchClear_Click(object sender, EventArgs e)
        {
            SellMediaSearch.Clear();
        }

        private void SellMediaSearchDisplay_Click(object sender, EventArgs e)
        {
            string toSearch = SellMediaSearch.Text;
            if (SellMediaSearchTitleRadio.Checked)
                searchMedia(toSearch, "ALBUM", SellMedia);
            else if (SellMediaSearchArtistRadio.Checked)
                searchMedia(toSearch, "ARTIST", SellMedia);
            else if (SellMediaSearchGenreRadio.Checked)
                searchMedia(toSearch, "GENRE", SellMedia);
            else
                MessageBox.Show("What do you want me to search by?");
        }

        private void SellCustSearchClear_Click(object sender, EventArgs e)
        {
            SellCustSearch.Clear();
        }

        private void SellCustSearchDisplay_Click(object sender, EventArgs e)
        {
            string toSearch = SellCustSearch.Text;
            if (SellCustSearchAddressRadio.Checked)
                searchCustomers(toSearch, "ADDRESS", SellCust);
            else if (SellCustSearchNameRadio.Checked)
                searchCustomers(toSearch, "NAME", SellCust);
            else if (SellCustSearchPhoneRadio.Checked)
                searchCustomers(toSearch, "PHONE", SellCust);
            else MessageBox.Show("What do you want me to search by?");
        }

        private void SellClear_Click(object sender, EventArgs e)
        {
            SellCust.ClearSelected();
            SellMedia.ClearSelected();
            SellPrice.Value = (decimal)0.00;
        }

        private void MedHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://dl.dropbox.com/u/4989354/MediaPageHelp.pdf");
        }

        private void CustHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://dl.dropbox.com/u/4989354/CustomersPageHelp.pdf");
        }

        private void BuyHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://dl.dropbox.com/u/4989354/BuyPageHelp.pdf");
        }

        private void SellHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://dl.dropbox.com/u/4989354/SellPageHelp.pdf");
        }

        private void ReportHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://dl.dropbox.com/u/4989354/ReportsPageHelp.pdf");
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {// This is the Rewards Program Help click event.
            System.Diagnostics.Process.Start("http://dl.dropbox.com/u/4989354/RewardsPageHelp.pdf");
        }

        private void RewardDispAllCust_Click(object sender, EventArgs e)
        {
            populateLists();
        }

        private void RewardCustSearchClear_Click(object sender, EventArgs e)
        {
            RewardCustSearch.Clear();
        }
        private void RewardCustSearchDisplay_Click(object sender, EventArgs e)
        {
            string toSearch = RewardCustSearch.Text;
            if (RewardCustSearchNameRadio.Checked)
                searchCustomers(toSearch, "NAME", RewardCustList);
            else if (RewardCustSearchAddressRadio.Checked)
                searchCustomers(toSearch, "ADDRESS", RewardCustList);
            else if (RewardCustSearchPhoneRadio.Checked)
                searchCustomers(toSearch, "PHONE", RewardCustList);
            else MessageBox.Show("What do you want me to search by?");
        }

        private void RewardClearData_Click(object sender, EventArgs e)
        {

        }

        private void RewardsCreateNewBOGO_Click(object sender, EventArgs e)
        {
            if (RewardsBuyNumber.Value == 0)
                MessageBox.Show("Customer must buy at least one item to get any free!");
            else
            {
                RewardProgram toAdd = new RewardProgram((int)RewardsBuyNumber.Value, (int)RewardsGetNumber.Value, RewardsBuyGetDescription.Text);
                try
                {
                    mainDB.rewardPrograms.Remove(toAdd.ToString());
                }
                catch (Exception) { }
                finally
                {
                    mainDB.rewardPrograms.Add(toAdd.ToString(), toAdd);
                }
                populateLists();
            }
        }

        private void RewardsCreateNewPercent_Click(object sender, EventArgs e)
        {
            RewardProgram toAdd = new RewardProgram((int)RewardsPercentageNumber.Value, RewardsPercentDescription.Text);
            try
            {
                mainDB.rewardPrograms.Remove(toAdd.ToString());
            }
            catch (Exception){            }
            finally
            {
                mainDB.rewardPrograms.Add(toAdd.ToString(), toAdd);
            }
            populateLists();
        }

        private void RewardsEnroll_Click(object sender, EventArgs e)
        {
            if (RewardCustList.SelectedItem == null || RewardProgramList.SelectedItem == null)
            {
                MessageBox.Show("Please select both, a customer, and a promotion");
            }
            else
            {
                string custString = RewardCustList.SelectedItem.ToString();
                custString = custString.Substring(custString.LastIndexOf(":") + 2);
                int custID = Int32.Parse(custString);
                PatsCustomer customer = mainDB.findCustomer(custID);
                customer.rewardProgram = mainDB.rewardPrograms[RewardProgramList.SelectedItem.ToString()];
                MessageBox.Show("Customer successfully added to rewards program!");
            }
            mainDB.Save();
        }

        private void RewardCustList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (RewardCustList.SelectedItem == null) return;
            string custString = RewardCustList.SelectedItem.ToString();
            custString = custString.Substring(custString.LastIndexOf(":") + 2);
            int custID = Int32.Parse(custString);
            PatsCustomer customer = mainDB.findCustomer(custID);

            RewardProgramList.SelectedItem = customer.rewardProgram.ToString();
        }

        private void RewardProgramList_SelectedIndexChanged(object sender, EventArgs e)
        {
            RewardProgramInfo.Text = mainDB.rewardPrograms[RewardProgramList.SelectedItem.ToString()].GetDesc();
        }
        void searchMedia(string toSearch, string searchBy, ListBox outputArea)
        {
            toSearch = toSearch.ToLower();
            searchBy = searchBy.ToUpper();
            outputArea.Items.Clear();
            foreach (Media m in mainDB.getAllMedia())
            {
                if (searchBy == "ALBUM" || searchBy == "TITLE")
                {
                    if (m.Title.ToLower().Contains(toSearch))
                        outputArea.Items.Add(m);
                }
                else if (searchBy == "ARTIST")
                {
                    if (m.Artist.ToLower().Contains(toSearch))
                        outputArea.Items.Add(m);
                }
                else if (searchBy == "GENRE")
                {
                    if (m.Genre.ToLower().Contains(toSearch))
                        outputArea.Items.Add(m);
                }
            }
            if (outputArea.Items.Count == 0) MessageBox.Show("No search results found!");
        }
        void searchCustomers(string toSearch, string searchBy, ListBox outputArea)
        {
            toSearch = toSearch.ToLower();
            searchBy = searchBy.ToUpper();
            outputArea.Items.Clear();
            foreach (PatsCustomer c in mainDB.getAllCustomers())
            {
                if (searchBy == "NAME")
                {
                    if (c.Name.ToLower().Contains(toSearch))
                        outputArea.Items.Add(c);
                }else if (searchBy == "ADDRESS")
                {
                    if (c.Address.ToLower().Contains(toSearch))
                        outputArea.Items.Add(c);
                }else if (searchBy == "PHONE")
                {
                    if (c.Name.ToLower().Contains(toSearch))
                        outputArea.Items.Add(c);
                }
            }
            if (outputArea.Items.Count == 0) MessageBox.Show("No search results found!");
        }

        private void RewardClearData_Click_1(object sender, EventArgs e)
        {
            RewardsBuyGetDescription.Clear();
            RewardsBuyNumber.Value = (decimal)1;
            RewardsGetNumber.Value = (decimal)0.00;
            RewardsPercentageNumber.Value = (decimal)0.00;
            RewardsPercentDescription.Clear();
        }
    }
}